<template>
  <div class="login-account">
    <el-form label-width="60px" :rules="rules" :model="account" ref="formRef">
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, defineExpose } from 'vue'
import { useStore } from 'vuex'
import { ElForm } from 'element-plus'

import { rules } from '../config/account-config'

import LocalCache from '@/untils/cache'

const account = reactive({
  name: LocalCache.getCache('name') ?? 'coderdemo',
  password: LocalCache.getCache('password') ?? '123456'
})
const formRef = ref<InstanceType<typeof ElForm>>()
const store = useStore()

const loginAction = (isKeepPassword: boolean) => {
  formRef.value?.validate((valid) => {
    if (valid) {
      // 是否记住密码
      if (isKeepPassword) {
        LocalCache.setCache('name', account.name)
        LocalCache.setCache('password', account.password)
      } else {
        LocalCache.deleteCache('name')
        LocalCache.deleteCache('password')
      }
      // 登录验证
      store.dispatch('login/accountLoginAction', { ...account })
    }
  })
}
defineExpose({
  loginAction
})
</script>

<style></style>
